package malus.shaofeng.com.beiwomusic.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

/**
 * Created by Casio on 2015/2/6.
 */

/**
 * 通用的图片下载异步任务，通过构造方法设置，需要接收图片的ImageView
 */
public  class ImageLoader extends AsyncTask<String,Integer,byte[]> {

    //用于引用外部的
    private ImageView myImageView;
    private String imgUrl;

    public ImageLoader(ImageView myImageView) {
        this.myImageView = myImageView;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        byte[] ret = new byte[0];

        if (params!=null && params.length>0){

            imgUrl = params[0];
            ret = HttpTool.get(imgUrl);
        }

        return ret;
    }


    @Override
    protected void onPostExecute(byte[] bytes) {

        if (bytes!=null){

            //更新文件缓存
            FileCache fileCache = FileCache.getInstance();
            fileCache.putContent(imgUrl,bytes);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

            //更新内存缓存
            ImageCache imageCache = ImageCache.getInstance();
            //向内存中设置图片缓存
            imageCache.putImage(imgUrl,bitmap);

            if (myImageView!=null){

                Object tag = myImageView.getTag();
                if (tag!=null){
                    if (tag instanceof String){
                        String sTag = (String) tag;
                        if (sTag.equals(imgUrl)){
                            myImageView.setImageBitmap(bitmap);
                        }
                    }
                }else {
                    myImageView.setImageBitmap(bitmap);
                }
            }

        }
    }
}
